package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单服务
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    /* @Autowired
     private UserDao userDao;*/
    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> getDynamicMenu(String username) {
        List<Menu> allMenu1 = menuDao.getAllMenu1(username);
        if (allMenu1 == null) {
            return null;
        }
        List<Menu> menuList = getChildrenMenu(allMenu1, username);
        return menuList;
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //当前页码
        Integer currentPage = queryPageBean.getCurrentPage();
        //每页记录数
        Integer pageSize = queryPageBean.getPageSize();
        //过滤条件
        String queryString = queryPageBean.getQueryString();
        //完成分页查询,基于Mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        if (queryString != null) {
            queryString = '%' + queryString + '%';
        }
        Page<Menu> page = menuDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Menu> rows = page.getResult();

        return new PageResult(total, rows);
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    @Override
    public void deleteById(Integer id) {

        long count = menuDao.findCountByMenuId(id);
        if (count > 0) {
           throw  new RuntimeException();
        }
        menuDao.deleteById(id);
    }

    public List<Menu> getChildrenMenu(List<Menu> allMenu1, String username) {
        for (Menu menu : allMenu1) {
            Integer id = menu.getId();
            List<Menu> children = menuDao.getChildrenMenuByParentMenuId(id, username);
            if (children != null) {
                getChildrenMenu(children, username);
            }
            menu.setChildren(children);
        }
        return allMenu1;
    }
    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }
    @Override
    public List<Integer> findMenuIdsByRoleId(Integer id) {
        List<Integer> menus = menuDao.findMenuIdsByRoleId(id);
        return menus;
    }
}
